<template>
	<view class="earnings-page">
		<!-- 收入统计卡片 -->
		<view class="earnings-card">
			<view class="card-header">
				<text class="card-title">收入统计</text>
				<picker 
					:range="periodOptions" 
					:value="periodIndex"
					@change="onPeriodChange"
				>
					<view class="period-selector">
						<text>{{ periodOptions[periodIndex] }}</text>
						<text class="arrow">▼</text>
					</view>
				</picker>
			</view>
			
			<view class="earnings-stats">
				<view class="stat-item main">
					<text class="stat-label">总收入</text>
					<text class="stat-value">￥{{ stats.totalEarnings || 0 }}</text>
				</view>
				
				<view class="stat-row">
					<view class="stat-item">
						<text class="stat-label">已结算</text>
						<text class="stat-value settled">￥{{ stats.settledEarnings || 0 }}</text>
					</view>
					<view class="stat-item">
						<text class="stat-label">待结算</text>
						<text class="stat-value pending">￥{{ stats.pendingEarnings || 0 }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 筛选栏 -->
		<view class="filter-bar">
			<picker 
				:range="statusOptions" 
				range-key="name"
				:value="statusIndex"
				@change="onStatusChange"
			>
				<view class="filter-item">
					<text>{{ statusOptions[statusIndex].name }}</text>
					<text class="arrow">▼</text>
				</view>
			</picker>
		</view>
		
		<!-- 收入记录列表 -->
		<scroll-view 
			class="earnings-scroll" 
			scroll-y 
			@scrolltolower="loadMore"
			refresher-enabled 
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<view class="earnings-item" v-for="record in earningsList" :key="record.id">
				<view class="earnings-header">
					<text class="order-title">{{ record.orderTitle }}</text>
					<text class="earnings-amount" :class="getAmountClass(record.status)">
						+￥{{ record.amount }}
					</text>
				</view>
				
				<view class="earnings-info">
					<view class="info-row">
						<text class="label">订单编号：</text>
						<text class="value">{{ record.orderNo || record.orderId }}</text>
					</view>
					<view class="info-row">
						<text class="label">完成时间：</text>
						<text class="value">{{ formatTime(record.completedTime) }}</text>
					</view>
					<view class="info-row">
						<text class="label">结算状态：</text>
						<text class="value" :class="getStatusClass(record.status)">
							{{ getStatusText(record.status) }}
						</text>
					</view>
					<view class="info-row" v-if="record.settledTime">
						<text class="label">结算时间：</text>
						<text class="value">{{ formatTime(record.settledTime) }}</text>
					</view>
				</view>
				
				<view class="earnings-actions" v-if="record.status === 'pending'">
					<button class="action-btn apply" @click="applySettlement(record.id)">
						申请结算
					</button>
				</view>
			</view>
			
			<view class="load-more" v-if="hasMore">
				<text v-if="loading">加载中...</text>
				<text v-else>上拉加载更多</text>
			</view>
			
			<view class="no-more" v-if="!hasMore && earningsList.length > 0">
				<text>没有更多数据了</text>
			</view>
			
			<view class="empty" v-if="!loading && earningsList.length === 0">
				<text>暂无收入记录</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				stats: {},
				earningsList: [],
				loading: false,
				refreshing: false,
				hasMore: true,
				pageNum: 1,
				pageSize: 10,
				periodIndex: 0,
				statusIndex: 0,
				periodOptions: ['本月', '上月', '近3个月', '全部'],
				statusOptions: [
					{ name: '全部状态', value: '' },
					{ name: '已结算', value: 'settled' },
					{ name: '待结算', value: 'pending' }
				]
			}
		},
		onLoad() {
			this.checkPermission()
			this.loadEarningsData()
		},
		methods: {
			checkPermission() {
				if (!this.$store || !this.$store.getters || !this.$store.getters.isTech) {
					uni.showToast({
						title: '权限不足',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
			},
			
			async loadEarningsData() {
				await Promise.all([
					this.loadStats(),
					this.loadEarningsList(true)
				])
			},
			
			async loadStats() {
				try {
					const period = this.getPeriodValue()
					const res = await this.$api.getTechEarningsStats({ period })
					if (res.code === 200) {
						this.stats = res.data
					}
				} catch (error) {
					console.error('加载统计数据失败:', error)
					// 模拟数据
					this.stats = {
						totalEarnings: 15600,
						settledEarnings: 12800,
						pendingEarnings: 2800
					}
				}
			},
			
			async loadEarningsList(refresh = false) {
				if (this.loading) return
				
				this.loading = true
				
				if (refresh) {
					this.pageNum = 1
					this.hasMore = true
				}
				
				try {
					const params = {
						pageNum: this.pageNum,
						pageSize: this.pageSize,
						period: this.getPeriodValue()
					}
					
					if (this.statusOptions[this.statusIndex].value) {
						params.status = this.statusOptions[this.statusIndex].value
					}
					
					const res = await this.$api.getTechEarningsList(params)
					
					if (res.code === 200) {
						const newRecords = res.data || []
						
						if (refresh) {
							this.earningsList = newRecords
						} else {
							this.earningsList = [...this.earningsList, ...newRecords]
						}
						
						this.hasMore = newRecords.length === this.pageSize
						this.pageNum++
					}
				} catch (error) {
					console.error('加载收入记录失败:', error)
					// 模拟数据
					if (refresh) {
						this.earningsList = [
							{
								id: 1,
								orderTitle: 'Vue.js项目开发',
								orderId: 'ORD001',
								amount: 3000,
								status: 'settled',
								completedTime: '2024-01-15 10:30:00',
								settledTime: '2024-01-16 14:20:00'
							},
							{
								id: 2,
								orderTitle: '微信小程序开发',
								orderId: 'ORD002',
								amount: 2500,
								status: 'pending',
								completedTime: '2024-01-20 16:45:00'
							}
						]
					}
				} finally {
					this.loading = false
					this.refreshing = false
				}
			},
			
			onRefresh() {
				this.refreshing = true
				this.loadEarningsData()
			},
			
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.loadEarningsList()
				}
			},
			
			onPeriodChange(e) {
				this.periodIndex = e.detail.value
				this.loadEarningsData()
			},
			
			onStatusChange(e) {
				this.statusIndex = e.detail.value
				this.loadEarningsList(true)
			},
			
			getPeriodValue() {
				const periodMap = {
					0: 'current_month',
					1: 'last_month',
					2: 'last_3_months',
					3: 'all'
				}
				return periodMap[this.periodIndex] || 'current_month'
			},
			
			async applySettlement(recordId) {
				uni.showModal({
					title: '申请结算',
					content: '确定要申请结算此笔收入吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$api.applySettlement(recordId)
								uni.showToast({
									title: '申请成功',
									icon: 'success'
								})
								this.loadEarningsList(true)
							} catch (error) {
								uni.showToast({
									title: error.message || '申请失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},
			
			getAmountClass(status) {
				return status === 'settled' ? 'settled' : 'pending'
			},
			
			getStatusClass(status) {
				return status === 'settled' ? 'status-settled' : 'status-pending'
			},
			
			getStatusText(status) {
				const statusMap = {
					'settled': '已结算',
					'pending': '待结算',
					'processing': '结算中'
				}
				return statusMap[status] || '未知'
			},
			
			formatTime(time) {
				if (!time) return ''
				const date = new Date(time)
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
			}
		}
	}
</script>

<style lang="scss" scoped>
	.earnings-page {
		background: #f5f5f5;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}
	
	.earnings-card {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		margin: 20rpx;
		border-radius: 20rpx;
		padding: 40rpx;
		color: #fff;
		
		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 40rpx;
			
			.card-title {
				font-size: 36rpx;
				font-weight: bold;
			}
			
			.period-selector {
				display: flex;
				align-items: center;
				background: rgba(255, 255, 255, 0.2);
				padding: 10rpx 20rpx;
				border-radius: 20rpx;
				font-size: 24rpx;
				
				.arrow {
					margin-left: 10rpx;
					font-size: 20rpx;
				}
			}
		}
		
		.earnings-stats {
			.stat-item {
				text-align: center;
				
				&.main {
					margin-bottom: 30rpx;
					
					.stat-label {
						display: block;
						font-size: 24rpx;
						opacity: 0.8;
						margin-bottom: 10rpx;
					}
					
					.stat-value {
						display: block;
						font-size: 48rpx;
						font-weight: bold;
					}
				}
			}
			
			.stat-row {
				display: flex;
				
				.stat-item {
					flex: 1;
					
					.stat-label {
						display: block;
						font-size: 24rpx;
						opacity: 0.8;
						margin-bottom: 10rpx;
					}
					
					.stat-value {
						display: block;
						font-size: 32rpx;
						font-weight: bold;
						
						&.settled {
							color: #4CAF50;
						}
						
						&.pending {
							color: #FFC107;
						}
					}
				}
			}
		}
	}
	
	.filter-bar {
		background: #fff;
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
		
		.filter-item {
			padding: 20rpx;
			background: #f8f8f8;
			border-radius: 10rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			
			.arrow {
				color: #999;
				font-size: 20rpx;
			}
		}
	}
	
	.earnings-scroll {
		flex: 1;
		padding: 20rpx;
	}
	
	.earnings-item {
		background: #fff;
		border-radius: 15rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		
		.earnings-header {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
			margin-bottom: 20rpx;
			
			.order-title {
				flex: 1;
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-right: 20rpx;
			}
			
			.earnings-amount {
				font-size: 32rpx;
				font-weight: bold;
				
				&.settled {
					color: #34c759;
				}
				
				&.pending {
					color: #ff9500;
				}
			}
		}
		
		.earnings-info {
			margin-bottom: 20rpx;
			
			.info-row {
				display: flex;
				margin-bottom: 10rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.label {
					font-size: 24rpx;
					color: #666;
					width: 140rpx;
				}
				
				.value {
					flex: 1;
					font-size: 24rpx;
					color: #333;
					
					&.status-settled {
						color: #34c759;
					}
					
					&.status-pending {
						color: #ff9500;
					}
				}
			}
		}
		
		.earnings-actions {
			.action-btn {
				width: 100%;
				height: 60rpx;
				border: none;
				border-radius: 30rpx;
				font-size: 24rpx;
				
				&.apply {
					background: #007bff;
					color: #fff;
				}
			}
		}
	}
	
	.load-more, .no-more {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.empty {
		text-align: center;
		padding: 200rpx 0;
		color: #999;
		font-size: 28rpx;
	}
</style>